package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.common.R;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    //发送验证码
    @PostMapping("/sendMsg")
    public R code(HttpServletRequest request, @RequestBody User user){
        String code = "";
        for (int i = 0; i < 6; i++) {
            int i1 = RandomUtils.nextInt(9);
            code+=i1;
        }
        String phone = user.getPhone();
        redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
        //request.getSession().setAttribute(phone,code);
        log.info(code);
        return R.success("验证码发送成功");
    }

    //登录
    @PostMapping("/login")
    public R login(HttpServletRequest request,@RequestBody User user){
        String phone = user.getPhone();
        //String o = (String) request.getSession().getAttribute(phone);
        String code = (String) redisTemplate.opsForValue().get(phone);
        //String code = user.getCode();
        if(!code.equals(user.getCode())){
            return R.error("您输入的验证码有误");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getPhone,phone);
        User one = userService.getOne(wrapper);
        if(one==null){
            userService.save(user);
            request.getSession().setAttribute("user",user);
        }else {
            request.getSession().setAttribute("user",one);
        }
        redisTemplate.delete(phone);
        return R.success("登录成功");
    }
    //退出登录
    @PostMapping("/loginout")
    public R loginOut(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }

    //


}

